<template>
  <div class="app-header-container">
    <!-- 顶部导航栏 -->
    <div class="nav-header">
      <div class="nav-header-container">
        <!-- 左侧：Logo和导航菜单 -->
        <div class="nav-header-left">
          <div class="logo" @click="goHome">
            <h1 class="logo-title">无限导航</h1>
          </div>
          
          <nav class="nav-menu">
            <a 
              class="nav-menu-item" 
              :class="{ active: route.path === '/' }"
              @click="goHome"
            >
              <el-icon><HomeFilled /></el-icon>
              <span>首页</span>
            </a>
            <a 
              class="nav-menu-item"
              :class="{ active: route.path === '/crawler' }"
              @click="goCrawler"
            >
              <el-icon><Link /></el-icon>
              <span>爬取工具</span>
            </a>
          </nav>
        </div>

        <!-- 右侧：工具和用户功能 -->
        <div class="nav-header-right">
          <!-- 新增按钮组 -->
          <div class="header-actions">
            <el-dropdown trigger="click" placement="bottom-end">
              <el-button type="primary" :icon="Plus" circle />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleAddFirstMenu">
                    <el-icon><Plus /></el-icon>
                    <span>新增一级菜单</span>
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleAddSecondMenu">
                    <el-icon><Plus /></el-icon>
                    <span>新增二级菜单</span>
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleAddWebsite" divided>
                    <el-icon><Plus /></el-icon>
                    <span>新增网站</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <!-- 主题切换按钮 -->
          <el-popover 
            ref="themePopoverRef"
            placement="bottom-end" 
            :width="300" 
            trigger="click"
          >
            <template #reference>
              <el-button circle class="theme-button" :icon="Brush" />
            </template>
            <div class="theme-picker">
              <div class="theme-picker-title">选择主题</div>
              <div class="theme-grid">
                <div
                  v-for="(theme, key) in themes"
                  :key="key"
                  class="theme-item"
                  :class="{ active: currentTheme === key }"
                  @click="handleThemeChange(key)"
                >
                  <div
                    class="theme-preview"
                    :style="{ background: theme.gradient }"
                  ></div>
                  <span class="theme-name">{{ theme.name }}</span>
                  <el-icon v-if="currentTheme === key" class="check-icon">
                    <Check />
                  </el-icon>
                </div>
              </div>
            </div>
          </el-popover>

          <!-- 用户功能 -->
          <div class="user-section">
            <!-- 未登录 -->
            <el-button
              v-if="!userInfos.isLogin"
              type="primary"
              class="login-button"
              @click="handleLogin"
              :icon="User"
            >
              <span>登录</span>
            </el-button>

            <!-- 登录后显示 -->
            <el-dropdown v-if="userInfos.isLogin" @command="handleCommand" trigger="click">
              <span class="user-dropdown">
                <el-avatar :size="32" class="user-avatar">
                  {{ userInfos.user.name?.charAt(0) || 'U' }}
                </el-avatar>
                <span class="user-name">{{ userInfos.user.name }}</span>
                <el-icon class="dropdown-icon">
                  <ArrowDown />
                </el-icon>
              </span>

              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="个人中心" :icon="User">
                    个人中心
                  </el-dropdown-item>
                  <el-dropdown-item command="退出登录" :icon="SwitchButton" divided>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
    </div>

    <!-- 个人中心 -->
    <personal-drawer ref="personalDrawerRef"></personal-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowDown,
  User,
  Link,
  SwitchButton,
  Brush,
  Check,
  Plus,
  HomeFilled,
} from '@element-plus/icons-vue'

import { logout } from '@/api/login/index'
import { useUserInfo } from '@/stores/userInfo'
import { Session } from '@/utils/storage'
import { themes, getCurrentTheme, setTheme } from '@/utils/theme'
import PersonalDrawer from '@/views/persion/index.vue'

/**
 * Emits 定义
 */
const emit = defineEmits<{
  /** 新增一级菜单事件 */
  'add-first-menu': []
  /** 新增二级菜单事件 */
  'add-second-menu': []
  /** 新增网站事件 */
  'add-website': []
  /** 主题切换事件 */
  'theme-change': [themeName: string]
}>()

/**
 * 组件引用
 */
const personalDrawerRef = ref<InstanceType<typeof PersonalDrawer> | null>(null)
const themePopoverRef = ref()

/**
 * 路由相关
 */
const router = useRouter()
const route = useRoute()

/**
 * 用户信息
 */
const userInfoStore = useUserInfo()
const userInfos = userInfoStore.userInfos

/**
 * 当前主题
 */
const currentTheme = ref(getCurrentTheme())

/**
 * 处理主题切换
 * @param themeName 主题名称
 */
function handleThemeChange(themeName: string) {
  currentTheme.value = themeName
  setTheme(themeName)
  ElMessage.success(`已切换到${themes[themeName].name}主题`)
  emit('theme-change', themeName)
  
  // 关闭主题选择下拉菜单
  if (themePopoverRef.value) {
    themePopoverRef.value.hide()
  }
}

/**
 * 处理新增一级菜单事件
 */
function handleAddFirstMenu() {
  emit('add-first-menu')
}

/**
 * 处理新增二级菜单事件
 */
function handleAddSecondMenu() {
  emit('add-second-menu')
}

/**
 * 处理新增网站事件
 */
function handleAddWebsite() {
  emit('add-website')
}

/**
 * 处理登录跳转
 */
function handleLogin() {
  router.push('/login')
}

/**
 * 跳转到首页
 */
function goHome() {
  router.push('/')
}

/**
 * 跳转到爬取工具页面
 */
function goCrawler() {
  router.push('/crawler')
}

/**
 * 处理下拉菜单命令
 * @param command 命令名称
 */
function handleCommand(command: string | number | object) {
  if (command === '退出登录') {
    ElMessageBox.confirm('确定退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      handleLogout()
      ElMessage({
        type: 'success',
        message: '退出成功',
      })
    })
  } else if (command === '个人中心') {
    // 打开个人中心抽屉
    personalDrawerRef.value!.open()
  }
}

/**
 * 退出登录
 * 清除前后端token并跳转到登录页
 */
function handleLogout() {
  // 1. 清除后端token
  logout()
  // 2. 清除前端缓存/token等
  Session.clear()
  // 3. 跳转到登录页面
  router.push('/login')
}
</script>

<style scoped lang="scss">
.app-header-container {
  width: 100%;
  position: relative;
}

/* 顶部导航栏 */
.nav-header {
  background: var(--theme-gradient);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  transition: background 0.3s ease, border-color 0.3s ease;
}

.nav-header-container {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 64px;
  padding: 0 24px;
  gap: 24px;
}

/* 左侧：Logo和导航菜单 */
.nav-header-left {
  display: flex;
  align-items: center;
  gap: 32px;
  flex-shrink: 0;
}

.logo {
  cursor: pointer;
  user-select: none;
  
  .logo-title {
    margin: 0;
    color: #ffffff;
    font-size: 24px;
    font-weight: 700;
    letter-spacing: 1px;
    transition: all 0.3s ease;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }
  
  &:hover .logo-title {
    transform: scale(1.05);
    opacity: 0.9;
  }
}

.nav-menu {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .nav-menu-item {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 8px 16px;
    color: rgba(255, 255, 255, 0.9);
    font-size: 14px;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s ease;
    text-decoration: none;
    white-space: nowrap;
    
    &:hover {
      color: #ffffff;
      background-color: rgba(255, 255, 255, 0.15);
    }
    
    &.active {
      color: #ffffff;
      background-color: rgba(255, 255, 255, 0.2);
      font-weight: 500;
    }
    
    .el-icon {
      font-size: 16px;
    }
  }
}


/* 右侧：工具和用户功能 */
.nav-header-right {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  
  :deep(.el-button--primary) {
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.3);
    color: #ffffff;
    
    &:hover {
      background: rgba(255, 255, 255, 0.3);
      border-color: rgba(255, 255, 255, 0.5);
    }
  }
}

.theme-button {
  color: rgba(255, 255, 255, 0.9);
  border-color: rgba(255, 255, 255, 0.3);
  background-color: rgba(255, 255, 255, 0.1);
  
  &:hover {
    color: #ffffff;
    border-color: rgba(255, 255, 255, 0.5);
    background-color: rgba(255, 255, 255, 0.2);
  }
}

.user-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

.login-button {
  padding: 8px 20px;
  font-size: 14px;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #ffffff;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  &:hover {
    background: rgba(255, 255, 255, 0.3);
    border-color: rgba(255, 255, 255, 0.5);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}

.user-dropdown {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    background-color: rgba(255, 255, 255, 0.15);
  }
}

.user-avatar {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #ffffff;
  font-weight: 600;
  flex-shrink: 0;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.9);
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.dropdown-icon {
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
  transition: transform 0.3s ease;
  flex-shrink: 0;
}

.user-dropdown:hover .dropdown-icon {
  transform: translateY(2px);
}


.theme-picker {
  padding: 16px;
}

.theme-picker-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  color: var(--theme-text);
  text-align: center;
}

.theme-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.theme-item {
  position: relative;
  padding: 12px;
  border-radius: 12px;
  border: 2px solid transparent;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f5f7fa;

  &:hover {
    border-color: var(--theme-primary);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  &.active {
    border-color: var(--theme-primary);
    background: rgba(102, 126, 234, 0.1);
  }
}

.theme-preview {
  width: 100%;
  height: 40px;
  border-radius: 8px;
  margin-bottom: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.theme-name {
  font-size: 13px;
  color: var(--theme-text);
  font-weight: 500;
}

.check-icon {
  position: absolute;
  top: 8px;
  right: 8px;
  color: var(--theme-primary);
  font-size: 18px;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .nav-header-container {
    padding: 0 16px;
    height: 56px;
    gap: 16px;
  }

  .logo .logo-title {
    font-size: 20px;
  }

  .nav-menu {
    gap: 4px;
    
    .nav-menu-item {
      padding: 6px 12px;
      font-size: 13px;
      
      span {
        display: none;
      }
    }
  }

  .user-name {
    display: none;
  }

}

@media (max-width: 480px) {
  .nav-header-container {
    padding: 0 12px;
    gap: 8px;
  }

  .logo .logo-title {
    font-size: 18px;
  }

  .nav-menu {
    display: none;
  }

  .header-actions {
    display: none;
  }

}
</style>
